package com.kye.express.business.jd.address_select;

import android.app.Dialog;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.base.utils.GsonUtils;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatFragment;
import com.kye.express.databinding.FragmentAddressBinding;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.SideBar;
import com.kye.express.view.ToastManager;
import com.kye.express.view.reclyerview.FastScrollRecyclerView;
import com.kye.lib.view.statuslayout.StatusLayout;
import com.kye.model.bean.address.AddressBean;
import com.kye.model.bean.user.User;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import net.yslibrary.android.keyboardvisibilityevent.util.UIUtil;

import java.util.List;

import io.reactivex.functions.Consumer;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * @author : Joe
 * @version : 1.0
 * @editor : Joe
 * @created : 31/01/2018
 * @updated : 31/01/2018
 * @description : <Description>
 * @update_reason : <UpdateReason>
 */

public class AddressSelectFragment extends BaseAppCompatFragment implements AddressSelectFragmentConstract.AddressFragmentView, AddressSelectViewBinder.OnAddressListener, SideBar.OnTouchingLetterChangedListener {

    private final static String TAG_ID = "TAG_ID";
    private final static String TAG_ADDRESS_SELECTED = "TAG_ADDRESS_SELECTED";

    public static AddressSelectFragment newInstanceForSelection(AddressSelectLevel addressSelectLevel, int id) {
        Bundle args = new Bundle();
        args.putSerializable(AddressSelectLevel.class.getSimpleName(), addressSelectLevel);
        args.putInt(TAG_ID, id);
        AddressSelectFragment fragment = new AddressSelectFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private AddressSelectFragment.OnAddressListOptionListener onAddressListOptionListener;
    private AddressSelectLevel addressCurrentLevel; // 地址层级选择级别
//    private AddressSelectLevel addressCurrentLevel; // 当前地层级级别
    private int id;
    private AddressBean selectedAddressBean;
    private FragmentAddressBinding binding;
    private AddressSelectFragmentConstract.AddressFragmentPresenter presenter;
    private MultiTypeAdapter adapter;
    private AddressSelectViewBinder addressSelectViewBinder;

    private Dialog dialog;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            id = getArguments().getInt(TAG_ID);
            addressCurrentLevel = (AddressSelectLevel) getArguments().getSerializable(AddressSelectLevel.class.getSimpleName());
        } else {
            id = savedInstanceState.getInt(TAG_ID);
            selectedAddressBean = savedInstanceState.getParcelable(TAG_ADDRESS_SELECTED);
            addressCurrentLevel = (AddressSelectLevel) savedInstanceState.getSerializable(AddressSelectLevel.class.getSimpleName());
        }
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        outState.putSerializable(AddressSelectLevel.class.getSimpleName(), addressCurrentLevel);
        outState.putInt(TAG_ID, id);
        outState.putParcelable(TAG_ADDRESS_SELECTED, selectedAddressBean);
        super.onSaveInstanceState(outState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_address, container, false);
        binding = DataBindingUtil.bind(view);
        presenter = new AddressSelectFragmentConstract.AddressFragmentPresenter();
        initViews(view, savedInstanceState);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        initEvents(savedInstanceState);
        super.onActivityCreated(savedInstanceState);
    }

    private void initViews(View view, Bundle savedInstanceState) {
        adapter = new MultiTypeAdapter();
        addressSelectViewBinder = new AddressSelectViewBinder(this);
        adapter.register(AddressBean.class, addressSelectViewBinder);
        binding.sidebar.setTextView(binding.selectedLetter);
        binding.addresses.setLayoutManager(new LinearLayoutManager(getActivity()));
        HorizontalDividerItemDecoration itemDecoration = new HorizontalDividerItemDecoration.Builder(getContext())
                .color(getResources().getColor(R.color.divider_two))
                .size((int) UIUtil.convertDpToPx(getContext(), 0.5f)).build();
        binding.addresses.addItemDecoration(itemDecoration);
        binding.addresses.setAdapter(adapter);
    }

    private void initEvents(Bundle savedInstanceState) {
        RxView.clicks(binding.llErrorServer.btErrorServerRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.llErrorNet.btErrorNetRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.llEmpty.btEmptyRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        binding.statusLayout.setOnLoadingListener(new StatusLayout.OnLoadingListener() {
            @Override
            public void onLoading() {
                /**
                 * 获取当前层级的地址数据
                 */
                presenter.getAddressList(addressCurrentLevel, id);
            }
        });
        binding.sidebar.setOnTouchingLetterChangedListener(this);
    }

    @Override
    protected void initData(@Nullable Bundle savedInstanceState) {
        presenter.bind(this);
        binding.statusLayout.showLoadingView();
    }

    @Override
    public void onUser(User user) {

    }

    @Override
    public void getAddressListSuccess(List<AddressBean> addressBeans) {
        binding.statusLayout.showContentView();
        /**
         * init data
         */
        adapter.setItems(addressBeans);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void getAddressListServerFailed(String msg) {
        binding.statusLayout.showErrorServerView();
        ToastManager.show(getActivity(), msg);
    }

    @Override
    public void getAddressListNetFailed(String message) {
        binding.statusLayout.showErrorNetworkView();
        ToastManager.show(getActivity(), message);
    }

    public void setOnAddressListOptionListener(OnAddressListOptionListener onAddressListOptionListener) {
        this.onAddressListOptionListener = onAddressListOptionListener;
    }

    @Override
    public void onAddressClicked(AddressBean item) {
        Logger.d("onAddressClicked : " + GsonUtils.toJsonString(item, true));
        selectedAddressBean = item;
        // todo : 如果当前是第三级地址，点击查询第四级时需要先获取数据是否有第四级数据
        if (addressCurrentLevel == AddressSelectLevel.ADDRESS_LEVEL_3_COUNTRY) {
            presenter.checkAddressTownAvailable(AddressSelectLevel.ADDRESS_LEVEL_3_COUNTRY, item.getId());
        } else {
            if (onAddressListOptionListener != null) {
                onAddressListOptionListener.onItemSelected(addressCurrentLevel, item, false);
            }
        }
    }

    @Override
    public void checkAddressAvailableSuccess(List<AddressBean> addressBeans) {
        if (onAddressListOptionListener != null) {
            onAddressListOptionListener.onItemSelected(addressCurrentLevel, selectedAddressBean, false);
        }
    }

    @Override
    public void checkAddressUnavailable(String message) {
        if (onAddressListOptionListener != null) {
            onAddressListOptionListener.onItemSelected(addressCurrentLevel, selectedAddressBean, true);
        }
    }

    @Override
    public void checkAddressTownAvailableFailed(String message) {
        ToastManager.show(getActivity(), message);
    }

    @Override
    public void onTouchingLetterChanged(String letter) {
        char l = letter.toCharArray()[0];
        int positionForSection = addressSelectViewBinder.getPositionForSection(l);
        if (positionForSection != -1) {
            FastScrollRecyclerView fastScrollRecyclerView = (FastScrollRecyclerView) binding.addresses;
            fastScrollRecyclerView.move(positionForSection);
        }
    }

    /**
     * 处理层级选择时的回调
     */
    public static interface OnAddressListOptionListener {
        void onItemSelected(AddressSelectLevel addressSelectLevel, AddressBean addressBean, boolean finish);
    }

    @Override
    public void onLoading() {
        dialog = KyeProgressDialog.show(getActivity(), dialog);
    }

    @Override
    public void onLoaded() {
        KyeProgressDialog.dismiss(dialog);
    }

}
